package com.example.mediamoudle.crop

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.SeekBar
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseActivity
import com.android.baselibrary.utils.ScreenUtils
import com.android.baselibrary.utils.dp2px
import com.android.baselibrary.utils.getDurationString
import com.example.mediamoudle.R
import com.example.mediamoudle.crop.VideoFrameView.RecycleViewScrollListener
import com.example.mediamoudle.databinding.ActivityVideoCropBinding
import com.example.mediamoudle.router.MediaRouterPath


/**
 * @author: Mr.You
 * @create: 2022-11-19 10:13
 * @description:视频裁剪
 **/
@Route(path = MediaRouterPath.MEDIA_CROP)
class VideoCropActivity :BaseActivity<ActivityVideoCropBinding>(), View.OnClickListener,
    SeekBar.OnSeekBarChangeListener {
    /**缩略图adapter*/
    private var mAdapter: ThumbAdapter? = null

    /** 缩略图*/
    private var thumnlist = ArrayList<VideoInfo>()

    companion object{
        const val MESSAGE = 0
        const val TAG = "TAGSSA"

       // const val VIDEO_URL = "/storage/emulated/0/DCIM/Camera/20221115_134123.mp4"
       const val VIDEO_URL = "/storage/emulated/0/DCIM/Camera/20221115_134123.mp4"
    }

    override fun getLayoutId(): Int {return R.layout.activity_video_crop
}
    private var screenWidth = 0
    private var mAverageMsPx =20 //每毫秒所占的px

    var isScroll = false
    var lastScrollX = 0
    var  isOverScaledTouchSlop =false
    var scrollPos = 0
    var  mScaledTouchSlop =0
    var isSeeking = false
    var mLeftProgressPos: Long = 0
    var mRightProgressPos: Long = 0
   // private var duration = 5134L
   private var duration = 21546L




   private  var videoBottomDialog: VideoBottomDialog?=null
    override fun initView() {

        videoBottomDialog = VideoBottomDialog(this)
        mBinding.tvEndDuration.text = getDurationString(duration)
        mBinding.progressBar.max = (duration/1000).toInt()
         playVideo(VIDEO_URL)
         screenWidth = ScreenUtils.getScreenWidth(this, false)
       // averagePxMs = (mMaxWidth * 1.0f / (mRightProgressPos - mLeftProgressPos));
        mAverageMsPx = (duration/ dp2px(this,50)*duration/1000).toInt()

        mBinding.viewFrameView.setRecycleViewScrollListener(object :RecycleViewScrollListener{
            override fun start() {
               // mBinding.videoPreview.start()
            }

            override fun pause() {
                mBinding.videoPreview.pause()
            }

            override fun seekToPosition(position: Long) {
                mBinding.tvBeginDuration.text = getDurationString((position).toLong())
               mBinding.videoPreview.seekTo(position.toInt())
            }

            override fun getPlayerState(): Boolean {
                return mBinding.videoPreview.isPlaying
            }

        })

    }
    @SuppressLint("ClickableViewAccessibility")
    override fun initListener() {
        mBinding.imagePlay.setOnClickListener(this)
        mBinding.imagePlayControl.setOnClickListener(this)
        mBinding.videoPreview.setOnClickListener {
            if (mBinding.videoPreview.isPlaying){
                mBinding.imagePlay.visibility = View.VISIBLE
                mBinding.videoPreview.pause()
                mBinding.imagePlayControl.isSelected = true
            }
        }

        mBinding.progressBar.setOnSeekBarChangeListener(this)
        mBinding.mRecyclerView.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

               if (isScroll){
                   var extent = recyclerView.computeHorizontalScrollExtent();
                   Log.i("TAGasd", "extent: $extent")
                   //整体的高度，注意是整体，包括在显示区域之外的
                   var range = recyclerView.computeHorizontalScrollRange();
                   Log.i("TAGasd", "range: $range")
                   //已经向下滚动的距离，为0时表示已处于顶部
                   var offset = recyclerView.computeHorizontalScrollOffset();
                   Log.i("TAGasd", "offset: $offset")
                   //已经滚动的百分比 [0.0-1.0]
                   var percentage = (offset / (range - extent).toFloat())
                   var currentTime = duration * percentage
                   if (mBinding.videoPreview.isPlaying) mBinding.videoPreview.pause()
                   mBinding.videoPreview.seekTo(currentTime.toInt())
               }

            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

        })

        mBinding.mRecyclerView.setOnTouchListener { v, event ->
            when(event.action){
                MotionEvent.ACTION_DOWN ->{

                    //1.按下记录坐标
                    isScroll = true
                }
                MotionEvent.ACTION_UP ->{
                    isScroll = false
                }

            }

            return@setOnTouchListener false
        }


    }
    private fun seekTo(msec: Long) {
        mBinding.videoPreview.seekTo(msec.toInt())
    }
    /**
     * 播放视频
     *
     * @auth sxy
     * @date 2022/9/28 17:45
     */
    private fun playVideo(stringExtra: String) {
        if (TextUtils.isEmpty(stringExtra)) {
            Toast.makeText(this, "文本路径错误", Toast.LENGTH_SHORT).show()
        } else {
            mBinding.imagePlayControl.isSelected = false
            mBinding.imagePlay.visibility =  View.GONE
            mBinding.videoPreview.seekTo(0)
            mBinding.videoPreview.setVideoPath(stringExtra)
            mBinding.videoPreview.setOnPreparedListener { mp ->
                mBinding.imagePlay.visibility = View.VISIBLE
                Log.i(TAG, "playVideo: time ->${mBinding.videoPreview.duration}")
            }
            mBinding.videoPreview.setOnCompletionListener {
                mBinding.imagePlayControl.isSelected = true
                mBinding.imagePlay.visibility = View.VISIBLE
            }

        }
        // 通过视频获取缩略图
        thumnlist.clear()
        thumnlist.add(VideoInfo(0))
        getGetFrameAtTime(0)
    }
    override fun onClick(v: View?) {
        when(v?.id){
            /**点击播放**/
            R.id.image_play ->{
                mBinding.imagePlay.visibility = View.GONE
                mBinding.videoPreview.start()
                mBinding.imagePlayControl.isSelected = false
                startHandler()
                //videoBottomDialog?.show()
            }
            /**暂停and播放按钮**/
            R.id.image_play_control ->{
                mBinding.imagePlayControl.isSelected = mBinding.videoPreview.isPlaying
                mBinding.imagePlay.visibility = if (mBinding.videoPreview.isPlaying) View.VISIBLE else View.GONE
                if (mBinding.videoPreview.isPlaying){
                    mBinding.videoPreview.pause()
                }else{
                    mBinding.videoPreview.start()
                    startHandler()
                }
            }
        }
    }

    override fun onResume() {
//        if (!mBinding.videoPreview.isPlaying && !mBinding.imagePlayControl.isSelected){
//            mBinding.imagePlayControl.isSelected = false
//            mBinding.imagePlay.visibility =  View.GONE
//            mBinding.videoPreview.start()
//            startHandler()
//        }

        super.onResume()
    }

    override fun onPause() {
        if (mBinding.videoPreview.isPlaying){
            mBinding.videoPreview.pause()
            mBinding.imagePlayControl.isSelected = false
            mBinding.imagePlay.visibility =  View.VISIBLE
        }
        super.onPause()
    }

    /**
     * * @Description 更新进度条
     * @Author yf
     * @Date 2022/11/15 13:50
     */
    private val handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler(){
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                MESSAGE ->{
                    val current =  mBinding.videoPreview.currentPosition
                    Log.i("TAGasdf", "handleMessage: $current")
                 //   Log.i("TAGas", "initPic1: ${px2dp(this@VideoCropActivity,(mBinding.mRecyclerView.layoutManager as LinearLayoutManager).getChildAt(0)?.measuredWidth!!)}")

                    mBinding.tvBeginDuration.text = getDurationString((current).toLong())
                    mBinding.progressBar.secondaryProgress = (current/1000)
                    mBinding.progressBar.progress =  (current/1000)
                   // move(current)
                    freshUI()
                    startHandler()
                }
            }
        }
    }
    /**
     * * @Description 发送消息更新进度条
     * @Author yf
     * @Date 2022/11/15 13:50
     */
    private fun startHandler(){
        if (mBinding.videoPreview.isPlaying){
            handler.sendEmptyMessageDelayed(MESSAGE,50)
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        handler.removeMessages(MESSAGE)
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        if (fromUser){
            mBinding.videoPreview.seekTo(progress)
            mBinding.progressBar.progress = progress
            mBinding.tvBeginDuration.text = getDurationString((progress*1000).toLong())
            startHandler()
        }
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
        mBinding.videoPreview.pause()
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
        mBinding.videoPreview.start()
        mBinding.imagePlay.visibility = View.GONE
        mBinding.imagePlayControl.isSelected = false

    }
    private fun initPic(){
        mAdapter = ThumbAdapter()
        // 添加时间轴
        mBinding.mRecyclerView?.addItemDecoration(RecyclerDivider(com.android.baselibrary.R.color.color_808080))

        mAdapter?.updateList(thumnlist as List<VideoInfo>)
        mBinding.mRecyclerView?.apply {
            layoutManager =
                LinearLayoutManager(this@VideoCropActivity, LinearLayoutManager.HORIZONTAL, false)
            adapter = mAdapter

        }
        thumnlist.add(VideoInfo(0))
        mBinding.viewFrameView.setThumbList(thumnlist)
            Log.i("TAGas", "initPic2: ${mAdapter!!}")

    }

    private fun freshUI() {
        window.decorView.post {
            Log.i("TAGas", "currentPosition:ss"+mBinding.imagePlayControl.isSelected)
            if (!mBinding.imagePlayControl.isSelected){
                val currentPosition = mBinding.videoPreview.currentPosition
                Log.i("TAGas", "currentPosition:$currentPosition")
                mBinding.viewFrameView.updateScroll(true, currentPosition.toLong()*1000)
            }
        }
    }

    private fun getGetFrameAtTime(time: Long) {

        if (time >= duration/1000) {
            // 如果超过了就返回，不要截取了
            initPic()
            return
        }
        val nextTime = time + 1
        var targetFrame = time.toLong() * 1000000
        if (targetFrame > 0) {
            targetFrame += 1000000
        }
        if (targetFrame<=duration*1000000){
            thumnlist.add(VideoInfo(targetFrame,VIDEO_URL,1))
            getGetFrameAtTime(nextTime)
        }
    }
    private var last = 0L
    private var totalDis = 0L
    private var ia = false
    public fun move(currentTime: Int) {

        val dis  = currentTime *((dp2px(this,50)*((duration/1000).toInt()-1))+screenWidth)/duration
        Log.i(TAG, "movesa1-: ${(dp2px(this,50)*((duration/1000)))}" )
        Log.i(TAG, "movesa2: ${screenWidth}" )

        Log.i(TAG, "movesa: ${((dp2px(this,50)*((duration/1000).toInt()))+screenWidth)}" )
       /* val layoutParams = mBinding.mRecyclerView?.layoutParams as FrameLayout.LayoutParams
        if (dis>0){
            layoutParams.leftMargin = (-dis).toInt()
        }else{
            layoutParams.leftMargin = (dis).toInt()
        }

        mBinding.mRecyclerView?.layoutParams = layoutParams*/
        Log.i(TAG, "movesa: $currentTime" )
        Log.i(TAG, "moves1: ")
      //  totalDis+=last
        val l = dis -last
        last = dis
        Log.i(TAG, "moves1totalDis: "+totalDis)
      //  mBinding?.mRecyclerView?.smoothScrollBy(l.toInt(),0)

    }


}